/*
 * core_mqtt.c
 *
 */
#include <stdio.h>
#include <string.h>

#include "user.h"
#include "mqtt_app.h"
#include "cJSON.h"
#include "net.h"
#include "hmi.h"
#include "IAP.h"

#define Qos0 0

uint32_t pub_id=0;
int32_t rid=0;

char mqtt_pub_topic[30]={0};
uint8_t update_refresh=0;

char mqtt_pay_load[2000]={0};

uint8_t mqtt_rev_sta=0;    //
extern uint8_t net_state;
void mqtt_publish(char *topc,int qos,char *pload)
{
	if(net_state==1)
	{
		HAL_UART_Transmit(&huart3,(uint8_t *)pload,strlen(pload),0xfff);
		printf("mqtt send:->%s\r\n",pload);
	}
}


int32_t mqtt_json_Parse(char *dat)
{
  cJSON *json,*c_action;
  json = cJSON_Parse(dat);			//解析数据包
	
  if (!json)
  {
    printf("Error before: [%s]\r\n", cJSON_GetErrorPtr());
		return -1;
  }
  else
  {
		cJSON *c_id=cJSON_GetObjectItem(json, "id");
		rid=c_id->valueint;
		printf("rid=%d\r\n",rid);
    c_action = cJSON_GetObjectItem(json, "action");
		if(c_action&&c_action->type==cJSON_String)
		{
			printf("action:%s\n",c_action->valuestring);
			
			
			if(strcmp(c_action->valuestring,"Upgrade")==0)
			{
				printf("Upgrade...\n");
				printf("*************************************\n");
				printf("*************************************\n");
				mqtt_rev_sta=1;
				
				
				IAP_Start_ConfigParam_set(IMEI,SoftVer,"test",1883);
				osDelay(500);
				SystemReset();
				
			}
			else
			if(strcmp(c_action->valuestring,"loginResponse")==0)
			{
				printf("loginResp ok\n");
				mqtt_rev_sta=1;
			}
			else
			if(strcmp(c_action->valuestring,"pingResponse")==0)
			{
				printf("pingResponse ok\n");
				mqtt_rev_sta=1;
			}
			else
			if(strcmp(c_action->valuestring,"postResponse")==0)
			{
				printf("postResponse ok\n");
				mqtt_rev_sta=1;
			}
			else
			if(strcmp(c_action->valuestring,"set")==0)
			{
				cJSON* c_data=cJSON_GetObjectItem(json, "data");
				if(c_data)
				{

							// 解析并打印jhq_power_switch  
							cJSON *Set_PSF_OpenTime_obj = cJSON_GetObjectItem(c_data, "Set_PSF_OpenTime");  
							if (Set_PSF_OpenTime_obj != NULL) 
							{
										printf("Set_PSF_OpenTime: %d\n", Set_PSF_OpenTime_obj->valueint);  
										Set_PSF_OpenTime = Set_PSF_OpenTime_obj->valueint;  
							}
							
							cJSON *work_mode_obj = cJSON_GetObjectItem(c_data, "work_mode");  
							if (work_mode_obj != NULL) 
							{
									printf("set work_mode: %d\n", work_mode_obj->valueint);
									if(work_mode!=work_mode_obj->valueint)
									{
										work_mode=work_mode_obj->valueint;
										if(work_mode==0)
										{
											CloseAll();
											work_mode=0;
											HMI_Page_switch(0);
										}
										else if(work_mode==1)
										{
												error_code=0;
												CloseAll();
												work_mode=1;
												HMI_Page_switch(1);
										}
									}
							}
							
							cJSON *open_door_obj = cJSON_GetObjectItem(c_data, "open_door");  
							if (open_door_obj != NULL) 
							{
									printf("open_door: %d\n", open_door_obj->valueint);
									if(open_door_obj->valueint)
									{
										
									}
							}
							
							
							
//						eeprom_save_all();
							mqtt_Response("setResponse",rid);
							update_refresh=100;  //1000ms
						  
				}
			}
		}
	}
  cJSON_Delete(json);
  return 0;
}



void mqtt_rev_callback(unsigned char *pay_load)
{
	mqtt_json_Parse((char *)pay_load);
}



int mqtt_login(void)
{
	uint16_t timout=0;
	mqtt_rev_sta=0;
	pub_id++;
	memset(mqtt_pay_load,0,sizeof(mqtt_pay_load));
	sprintf(mqtt_pay_load,"{\"action\": \"login\",\"id\":%d,\"imei\":\"%s\",\"iccid\":\"%s\",\"osVersion\":\"%s\",\"lat\":\"%f\",\"long\":\"%f\"}",pub_id,IMEI,ICCID,SoftVer,LBS_lat,LBS_lng);
	mqtt_publish(mqtt_pub_topic,Qos0,mqtt_pay_load);
	
	while(timout++<MQTT_TIME_OUT_DEF)
	{
		if(mqtt_rev_sta==1)
		{
			return 0;
		}
		delay_ms(10);
	}
	return -1;
}


int mqtt_heartbeat(void)
{
	
	uint16_t timout=0;
	mqtt_rev_sta=0;
	memset(mqtt_pay_load,0,sizeof(mqtt_pay_load));
	pub_id++;
//	sprintf(mqtt_pay_load,"{\"action\": \"ping\",\"id\":%d,\"csq\":%d,\"err_code\":%d,\"ht_temp\":%d,\"igbt_temp\":%d,\"tol_tim\":%d,\"tol_pwr\":%d,\"v_rms\":%d,\"i_rms\":%.1f}",
//	pub_id,csq,induc_cooker.error_code,(uint16_t)Control_Temp,induc_cooker.igbt_temp,induc_cooker.dev_use_time,induc_cooker.tol_power_con,(uint16_t)induc_cooker.v_rms,induc_cooker.i_rms);
	sprintf(mqtt_pay_load,"{\"action\": \"ping\",\"id\":%d,\"csq\":%d,\"err_code\":%d}",
	pub_id,csq, 0);

	mqtt_publish(mqtt_pub_topic,Qos0,mqtt_pay_load);
	
	while(timout++<MQTT_TIME_OUT_DEF)
	{
		if(mqtt_rev_sta==1)
		{
			return 0;
		}
		delay_ms(10);
	}
	return -1;
}


//#define YW_DIN				//液位
//#define SW_DIN				//水位
//#define TGX_DIN 			//推杆下
//#define TGS_DIN 		  //推杆上
//#define JS_DIN  			//计数
//#define MC_DIN  			//门磁


//#define JR_OUT  	//加热
//#define DC2_OUT //电磁阀1
//#define DC1_OUT //电磁阀2
//#define GY_OUT  //刮油电机
//#define XH_OUT  //循环水泵
//#define WD_OUT  //网带电机
//#define TS_OUT  //提升电机
//#define SB_OUT  //水泵
//#define PS_OUT   //排水球阀


int mqtt_data_update(void)
{
	memset(mqtt_pay_load,0,sizeof(mqtt_pay_load));
	pub_id++;
    sprintf(mqtt_pay_load,  
            "{\"action\":\"post\",\"id\":%d,\"data\":{\"Set_PSF_OpenTime\":%d,\"Set_DCF1_OpenTime\":%d,\
\"Set_DCF2_OpenTime\":%d,\"Set_TSDJ_OverTime\":%d,\"Set_Volum\":%d,\"Set_FSDJ_Curr\":%d,\"Set_TSDJ_Curr\":%d,\
\"Set_Heat_Max\":%d,\"Set_Heat_Min\":%d,\"Set_PassWord\":%d,\"work_mode\":%d,\"JR_OUT\":%d,\"DC2_OUT\":%d,\"DC1_OUT\":%d,\
\"GY_OUT\":%d,\"XH_OUT\":%d,\"WD_OUT\":%d,\"TS_OUT\":%d,\"SB_OUT\":%d,\"PS_OUT\":%d,\"YW_DIN\":%d,\"SW_DIN\":%d,\
\"TGX_DIN\":%d,\"TGS_DIN\":%d,\"JS_DIN\":%d,\"MC_DIN\":%d,\"error_code\":%d,\
\"FSDJ_state\":%d,\"NtcTemp1\":%.1f,\"NtcTemp2\":%.1f,\"Oil_Weigh1\":%.1f,\"i_rms1\":%.2f,\"i_rms2\":%.2f,\
\"accuOil_Weigh\":%.1f,\"Total_Time\":%d}}",  
            pub_id,Set_PSF_OpenTime, Set_DCF1_OpenTime, Set_DCF2_OpenTime, Set_TSDJ_OverTime, Set_Volum, Set_FSDJ_Curr, Set_TSDJ_Curr, Set_Heat_Max, Set_Heat_Min, Set_PassWord, work_mode,
(uint8_t)JR_OUT,(uint8_t)DC2_OUT,(uint8_t)DC1_OUT,(uint8_t)GY_OUT,(uint8_t)XH_OUT,(uint8_t)WD_OUT,(uint8_t)TS_OUT,(uint8_t)SB_OUT,(uint8_t)PS_OUT,(uint8_t)YW_DIN,(uint8_t)SW_DIN,(uint8_t)TGX_DIN,(uint8_t)TGS_DIN,(uint8_t)JS_DIN,(uint8_t)MC_DIN
,error_code, FSDJ_STATE, Temp1, Temp2, Weigh1, i_rms1, i_rms2, (double)accuOil_Weigh/10.0,Total_Time);
	
	
	
	
	mqtt_publish(mqtt_pub_topic,Qos0,mqtt_pay_load);
	return 0;
}



int mqtt_data_update_oil(void)
{
	memset(mqtt_pay_load,0,sizeof(mqtt_pay_load));
	pub_id++;
    sprintf(mqtt_pay_load,  
            "{\"action\":\"postSingleOil\",\"id\":%d,\"data\":{\"singleOil_Weigh\":%.1f}",  
            pub_id, (double)singleOil_Weigh/10.0);
						
	mqtt_publish(mqtt_pub_topic,Qos0,mqtt_pay_load);
	return 0;
}




int mqtt_Response(const char *resp,unsigned int rid)
{
	memset(mqtt_pay_load,0,sizeof(mqtt_pay_load));
  sprintf(mqtt_pay_load, "{\"action\":\"%s\",\"id\":%d,\"result\":0}",resp,rid);  
	mqtt_publish(mqtt_pub_topic,Qos0,mqtt_pay_load);
	return 0;
}






//int mqtt_cmd_updateCookbook(unsigned short cookbook_id,unsigned int pid)
//{
//	memset(mqtt_pay_load,0,sizeof(mqtt_pay_load));
////	pub_id++;
//	cJSON* root = cJSON_CreateObject();
//	cJSON* action = cJSON_CreateString("command");
//	cJSON* command = cJSON_CreateString("uploadCookbook");
//	cJSON* id = cJSON_CreateNumber(pid);
//  cJSON* data=cJSON_CreateObject();
//  
//	
//	cJSON_AddItemToObject(root, "action", action);
//	cJSON_AddItemToObject(root, "command", command);
//	cJSON_AddItemToObject(root, "re_id", id);
//	cJSON_AddItemToObject(root, "data", data);
//	
//	cJSON* cookbook_index = cJSON_CreateNumber(cookbook_id);
//	cJSON_AddItemToObject(data, "cookbook_index", cookbook_index);
//	cJSON* book_name = cJSON_CreateString(cook_book[cookbook_id].cook_book_name);
//	cJSON_AddItemToObject(data, "book_name", book_name);
//	
//	cJSON *array = cJSON_CreateArray();
//	cJSON_AddItemToObject(data, "steps", array);
//	
//	for(int i=0;i<8;i++)
//	{
//		if(cook_book[cookbook_id].step[i].set_time!=0)
//		{
//			
//			cJSON *obj = cJSON_CreateObject();
//			cJSON_AddItemToArray(array, obj);
//			
//			cJSON* content =   cJSON_CreateString(cook_book[cookbook_id].step[i].content);
//			cJSON* set_time =  cJSON_CreateNumber(cook_book[cookbook_id].step[i].set_time);
//			cJSON* set_power = cJSON_CreateNumber(cook_book[cookbook_id].step[i].set_power);
//			cJSON* set_temp =  cJSON_CreateNumber(cook_book[cookbook_id].step[i].set_temp);
//			cJSON* mode = 	   cJSON_CreateNumber(cook_book[cookbook_id].step[i].mode_id);
//			cJSON* voiceid =   cJSON_CreateNumber(cook_book[cookbook_id].step[i].voice_id);
//			
//			cJSON_AddItemToObject(obj, "content", content);
//			cJSON_AddItemToObject(obj, "set_time", set_time);
//			cJSON_AddItemToObject(obj, "set_power", set_power);
//			cJSON_AddItemToObject(obj, "set_temp", set_temp);
//			cJSON_AddItemToObject(obj, "mode", mode);
//			cJSON_AddItemToObject(obj, "voiceid", voiceid);
//		}
//		else
//		{
//			break;
//		}
//	}
//	
//	//3. 打印生成的结果
//	char *json_data=cJSON_PrintUnformatted(root);
//	printf("json_data len%d:%s\n",strlen(json_data), json_data);
//	mqtt_publish(mqtt_pub_topic,Qos0,json_data);
//	cJSON_Delete(root); 
//	vPortFree(json_data);   //一定要free哦
//	return 0;
//}










